
const express = require("express");
const jsonwebtoken = require("jsonwebtoken");
const fsP = require("fs").promises;
const path = require("path");
const router = express.Router();
const userModel = require("../model/user.js");
const diarybookModel = require("../model/diarybook.js");
const diaryItemModel = require("../model/diaryItems.js");
const replyModel = require("../model/reply.js");
const remindModel = require("../model/remind.js");
const {send , sendErr} = require("./send");

router.get('/user' , async function(req , res){ // 获取用户数据
    try {
        let { userId } = req.query;
        let user = await userModel.findById(userId);
        let data = { ...user._doc };
        delete data.password;
        delete data.__v;
        delete data._id;
        if (user) {
            send(res, { data })
        } else {
            sendErr(res, { msg: "用户不存在" })
        }
    } catch (error) {
        console.log(error);
        sendErr(res, { msg: "传入的数据可能有问题" });
    }
})

router.get("/user/atLoneliness" , async function(req , res){
    try{
        let users = await userModel.find({atLoneliness : true});
        let arr = [];
        for(let i = 0 ; i < 15 ; i++){
            if(users[i]){
                let data = { ...users[i]._doc };
                delete data.password;
                delete data.__v;
                arr.push(data);
            } else break;
        }
        send(res , {data:arr});
    } catch (error) {
        console.log(error);
        sendErr(res, { msg: "传入的数据可能有问题" });
    }
})

router.post("/user/login" , async function(req , res){ // 登录
    try {
        let { email, tel, password } = req.body;

        if (email) {
            let user = await userModel.findOne({ email, password });
            if (user) {
                let token = jsonwebtoken.sign({ id: user._id }, 'HCS_come_on_baby', { expiresIn: '2day' });
                send(res, {
                    data: {
                        token,
                        userId: user._id
                    }
                })
            } else {
                sendErr(res, { msg: "邮箱或密码错误" })
            }
        } else {
            let user = await userModel.findOne({ tel, password });
            if (user) {
                let token = jsonwebtoken.sign({ id: user._id }, 'HCS_come_on_baby', { expiresIn: '2day' });
                send(res, {
                    data: {
                        token,
                        userId: user._id
                    }
                })
            } else {
                sendErr(res, { msg: "电话或密码错误" });
            }
        }
    } catch (error) {
        console.log(error);
        sendErr(res, { msg: "传入的数据可能有问题" });
    }
})

router.post("/user/register" , async function(req , res){ // 注册
    try {
        let { username, createAt, password, tel } = req.body;
        let user = await userModel.findOne({ tel });
        if (user) {
            sendErr(res, { msg: "该手机号已被注册" });
        } else {
            user = await userModel.create({
                username,
                createAt,
                password,
                tel
            })
            let token = jsonwebtoken.sign({ id: user._id }, 'HCS_come_on_baby', { expiresIn: '2day' });
            send(res, {
                data: {
                    token,
                    userId: user._id
                }
            })
        }
    } catch (error) {
        console.log(error);
        sendErr(res, { msg: "传入的数据可能有问题" });
    }
})

router.post("/user/revise" , async function(req , res){ // 修改
    try {
        let { userId, username, description, atLoneliness } = req.body;
        let user = await userModel.findById(userId);
        if (user) {
            let obj = {};
            if (username) obj.username = username;
            if (description) obj.description = description;
            if (atLoneliness) obj.atLoneliness = atLoneliness;

            await userModel.findByIdAndUpdate({ _id: userId }, { ...obj });
            send(res);
        } else {
            sendErr(res, { msg: "用户不存在" });
        }
    } catch (error) {
        console.log(error);
        sendErr(res, { msg: "传入的数据可能有问题" });
    }
})

router.post("/user/revise/email" , async function(req , res){ // 修改邮箱
    try {
        let { userId, password, newemail } = req.body;
        let user = await userModel.findOne({ _id: userId, password });
        if (user) {
            await userModel.findByIdAndUpdate(userId, { email: newemail });
            send(res);
        } else {
            sendErr(res, { msg: "密码错误" });
        }
    } catch (error) {
        console.log(error);
        sendErr(res, { msg: "传入的数据可能有问题" });
    }
})

router.post("/user/revise/pswd", async function (req, res) { // 修改密码
    try {
        let { userId, password, newpassword } = req.body;
        let user = await userModel.findOne({ _id: userId, password });
        if (user) {
            await userModel.findByIdAndUpdate(userId, { password: newpassword });
            send(res);
        } else {
            sendErr(res, { msg: "密码错误" });
        }
    } catch (error) {
        console.log(error);
        sendErr(res, { msg: "传入的数据可能有问题" });
    }
})

router.post("/user/focus" , async function(req , res){ // 关注和取消关注
    try {
        let { userId, idolId } = req.body;
        let fans = await userModel.findById(userId);
        if (fans) {
            let idol = await userModel.findById(idolId);
            if (idol) {
                let fansIds = idol.fansId;
                let index = -1;
                for (let i = 0; i < fansIds.length; i++) {
                    if (fansIds[i] === userId) {
                        index = i;
                        break;
                    }
                }

                if (index === -1) { // 没关注时关注,并创建提醒。
                    await userModel.findByIdAndUpdate(idolId, { "$push": { fansId: userId } });
                    await userModel.findByIdAndUpdate(userId, { "$push": { idolId } });
                    await remindModel.create({
                        idolId,
                        fansId: userId
                    })
                    send(res);
                } else { // 取消关注 并删除提醒
                    await userModel.findByIdAndUpdate(idolId, { $pull: { fansId: userId } });
                    await userModel.findByIdAndUpdate(userId, { $pull: { idolId: idolId } });
                    await remindModel.findOneAndDelete({ idolId });
                    send(res);
                }

            }
        } else {
            sendErr(res, { msg: "用户不存在" });
        }
    } catch (error) {
        console.log(error);
        sendErr(res, { msg: "传入的数据可能有问题" });
    }
})

router.delete("/user/:userId" , async function(req , res){ // 注销
    try {
        let { userId } = req.params;
        let user = await userModel.findById(userId);
        if (user) {
            for (let id of user.diarybookId) { // 删除日记本
                let diarybook = await diarybookModel.findById(id);
                for (let itemId of diarybook.diaryItems) { // 删除日记
                    let diaryItem = await diaryItemModel.findById(itemId);
                    for (let replyId of diaryItem.replyId) { // 删除自己日记的回复
                        await replyModel.findByIdAndDelete(replyId);
                    }
                    await diaryItemModel.findByIdAndDelete(itemId);
                }
                await diarybookModel.findByIdAndDelete(id);
            }
            for (let id of user.idolId) { // 删除user关注的粉丝
                await userModel.findByIdAndUpdate(id, { $pull: { fansId: userId } });
            }
            for (let id of user.fansId) { // 删除user粉丝的关注
                await userModel.findByIdAndUpdate(id, { $pull: { idolId: userId } });
            }
            let replys = await replyModel.find({ authorId: userId });
            for (let reply of replys) { // 删除user回复别人的回复
                await diaryItemModel.findByIdAndUpdate(reply.diaryItemId, { $pull: { replyId: reply._id } });
                await replyModel.findByIdAndDelete(reply._id);
            }
            if (user.headphoto !== "/static/headphoto/default.jpg"); // 删除头像
            await fsP.unlink(path.join(__dirname, `..${user.headphoto}`));
            await userModel.findByIdAndDelete(userId);
            send(res);
        } else {
            sendErr(res, { msg: "用户不存在" });
        }
    } catch (error) {
        console.log(error);
        sendErr(res, { msg: "传入的数据可能有问题" });
    }
})

router.post('/user/rebirth' , async function(req , res){ // 账号重生
    try {
        let { userId, password } = req.body;
        let user = await userModel.findOne({ _id: userId, password });
        if (user) {
            let newuser = await userModel.create({
                username: user.username,
                password: user.password,
                tel: user.tel,
                createAt: user.createAt,
                headphoto: user.headphoto,
                email: user.email,
                diarybookId: user.diarybookId
            })

            let replys = await replyModel.find({ authorId: userId });
            for (let reply of replys) { // 删除user回复别人的回复
                let diaryItem = await diaryItemModel.findById(reply.diaryItemId);
                if (diaryItem.authorId === userId) continue;
                await diaryItemModel.findByIdAndUpdate(reply.diaryItemId, { $pull: { replyId: reply._id } });
                await replyModel.findByIdAndDelete(reply._id);
            }

            for (let id of user.diarybookId) { // 修改日记本
                let diarybook = await diarybookModel.findById(id);
                for (let itemId of diarybook.diaryItems) { // 修改日记
                    await diaryItemModel.findByIdAndUpdate(itemId, { authorId: newuser._id });
                }
                await diarybookModel.findByIdAndUpdate(id, { authorId: newuser._id });
            }
            for (let id of user.idolId) { // 删除user关注的粉丝
                await userModel.findByIdAndUpdate(id, { $pull: { fansId: userId } });
            }
            for (let id of user.fansId) { // 删除user粉丝的关注
                await userModel.findByIdAndUpdate(id, { $pull: { idolId: userId } });
            }
            let data = { ...newuser._doc };
            delete data.password;
            delete data.__v;
            delete data._id;
            send(res, { data });
        } else {
            sendErr(res, { msg: "密码错误" });
        }
    } catch (error) {
        console.log(error);
        sendErr(res, { msg: "传入的数据可能有问题" });
    }
})

module.exports = router;